﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
using System.Security.Principal;
using System.Net;

namespace slCommunicator
{
    public static class ConsoleCommandLine
    {
        private static string exePath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;

        public static void Pre(string[] args)
        {
            if (args.Length > 0)
            {
                if (args.Length == 2)
                {
                    if (args[0] == "restart")
                        System.Diagnostics.Process.GetProcessById(int.Parse(args[1])).WaitForExit();
                }
                    // ** THERE ARE ALWAYS PEOPLE WANTING TO DO BAD THINGS
                    // ** IN CASE ANYONE DECIDES TO TURNS THIS INTO A SPY VIRUS, LETS LEAVE THE BASICS PREPARED ;) (it cannot be avoided really)
                else if (args.Length == 1)
                {
                    if (args[0] == "fullsilentinstall")
                    {
                        string installdir = Environment.ExpandEnvironmentVariables(localization.install_targetDir);
                        DirectoryCopy(Path.GetDirectoryName(exePath), installdir, false);
                        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Path.Combine(installdir, Path.GetFileName(exePath)), "silentregistryinstall"));

                        return;
                    }
                    else if (args[0] == "silentregistryinstall")
                    {
                        var r = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                        r.SetValue("SLComm", string.Format("\"{0}\" runsilent", exePath));
                    }
                }
                else if (args.Length == 5)
                {
                    if (args[0].Contains("scheduledcall"))
                    {
                        int port; IPAddress ip; char mode = '0'; TimeSpan time1;
                        if (!IPAddress.TryParse(args[1], out ip) || !int.TryParse(args[2], out port)
                            || !char.TryParse(args[3], out mode) || !TimeSpan.TryParse(args[4], out time1))
                        {
                            Console.WriteLine(localization.console_badSyntax);
                            return;
                        }

                        var delay = (mode == 'r' || mode == 'R') ? time1 : (time1 - DateTime.Now.TimeOfDay);
                        new System.Threading.Thread(new System.Threading.ThreadStart(delegate
                            {
                                System.Threading.Thread.Sleep(delay);
                                if (Session.currentSession == null)
                                    CallStarter.Call(new IPEndPoint(ip, port));
                            })).Start();
                    }
                }
                if (args[0].Contains("silent"))
                {
                    var hwnd = GetConsoleWindow();
                    ShowWindow(hwnd, SW_HIDE);
                }
            }

            Console.WriteLine(localization.console_greetings);
        }
        public static void Post()
        {
            Console.WriteLine(localization.console_waitingforcommand);
            while (true)
            {
                string line = Console.ReadLine().ToLower();
                if (string.IsNullOrEmpty(line) || string.IsNullOrWhiteSpace(line))
                    continue;

                string[] par = line.Split(' ');
                if (par[0] == "call")
                {
                    int port; IPAddress ip;
                    if (IPAddress.TryParse(par[1], out ip) && int.TryParse(par[2], out port))
                        CallStarter.Call(new IPEndPoint(ip, port));
                    else
                        Console.WriteLine(localization.console_badSyntax);
                }
                else if (par[0] == "config")
                    SettingsForm.ShowMe();
                else if (par[0] == "findpeers")
                    Register.PrintTodayJoinLog();
                else if (par[0] == "help")
                    Console.WriteLine(localization.console_helpString);
                else
                    Console.WriteLine(localization.console_commandunknown);
            }
        }

        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        const int SW_HIDE = 0;
        const int SW_SHOW = 5;

        private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException();
            }

            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string temppath = Path.Combine(destDirName, file.Name);
                file.CopyTo(temppath, false);
            }

            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = Path.Combine(destDirName, subdir.Name);
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs); // one must love recursion
                }
            }
        }
    }
}
